package com.cuit.mimall.controller.api;

import com.cuit.mimall.common.R;
import com.cuit.mimall.dto.LoginRequest;
import com.cuit.mimall.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : TeaWu
 * @folder API
 */
@RestController
@RequestMapping("/api/v1")
public class LoginController {
    private final LoginService loginService;

    @Autowired
    public LoginController(LoginService loginService) {
        this.loginService = loginService;
    }

    /**
     * 用户登录
     *
     * @param loginRequest 登录请求
     * @return 登录结果
     */
    @PostMapping("/login")
    public R<?> authenticateUser(@RequestBody LoginRequest loginRequest, HttpServletResponse response) {
        // 假设你已经生成了一个token
        String token = loginService.login(loginRequest);
        // 创建一个新的Cookie对象, 名称为'XM_TOKEN', 值为token
        Cookie cookie = new Cookie("XM_TOKEN", token);
        // 将Cookie添加到HTTP响应中
        response.addCookie(cookie);
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        return R.ok("登录成功", map);
    }

    /**
     * 用户注销
     *
     * @return 注销结果
     */
    @PostMapping("/logout")
    public R<?> logout() {
        return loginService.logout();
    }
}
